package com.dlry.serviceImpl.dwr;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dlry.entity.DlMeetingRoomBooking;
import com.dlry.serviceImpl.MeetingRoomService;

import net.sf.json.JSONObject;

@Service
public class EventObjectService {
	public EventObjectService() {
	}
	@Autowired
	private MeetingRoomService roomService;

	public List<JSONObject> getEventObjectsStart(String date, Long roomId) {
		System.out.println(roomId);
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		Date start = null;
		try {
			start = format1.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(start);
		calendar.add(Calendar.DATE, 41);
		Date end = calendar.getTime();
		Timestamp starttamp = new Timestamp(start.getTime());
		Timestamp endtamp = new Timestamp(end.getTime());
		List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
		List<DlMeetingRoomBooking> bookings = roomService.getBookingsByIdBetween(roomId, starttamp, endtamp);
		if (bookings == null) {
			return null;
		} else {
			for (DlMeetingRoomBooking booking : bookings) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date start2 = booking.getBookingTime();
				Timestamp end2 = booking.getEndTime();
				JSONObject object = new JSONObject();
				object.put("id", booking.getId());
				object.put("title", booking.getName());
				object.put("start", format.format(start2));
				object.put("end", format.format(end2));
				jsonObjects.add(object);
			}
			return jsonObjects;
		}
	}

	public List<JSONObject> getEventObjects(Date start, Date end, Long roomId) {
		System.out.println(roomId);
		List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
		Timestamp starttamp = new Timestamp(start.getTime());
		Timestamp endtamp = new Timestamp(end.getTime());
		List<DlMeetingRoomBooking> bookings = roomService.getBookingsByIdBetween(roomId, starttamp, endtamp);
		if (bookings == null) {
			return null;
		} else {
			for (DlMeetingRoomBooking booking : bookings) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				Date start2 = booking.getBookingTime();
				Timestamp end2 = booking.getEndTime();
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("id", booking.getId());
				jsonObject.put("title", booking.getName());
				jsonObject.put("start", format.format(start2));
				jsonObject.put("end", format.format(end2));
				jsonObjects.add(jsonObject);
			}
			return jsonObjects;
		}
	}

	public String dwrTest() {
		return "test";
	}
}
